<script>
//按需导入
import {ElMessage} from 'element-plus';
// 默认导入
import useCustomerStore from '@/stores/customer';
// 获得customerStore实例
const customerStore = useCustomerStore();

export default {
  name: "Login",
  data() {
      return {
          account: '',
          password: ''
      }
  },
  methods: {
      login() {
          // 对 account 和 password 进行非空检查和格式检查

          // 检查账号(即登录名称)是否可用
          const url = `/back/customer/usable/${this.account}`;
          this.axios.get(url).then(resp => {
              if( resp.data.success ) {
                ElMessage({message: `警告: 账号在系统中不存在！`, type: 'warning'});
                return;
              }
              // 发起新的请求并返回一个新的Promise实例
              return this.axios.post('/back/customer/sign/in',{account: this.account, password: this.password})
          }).then( resp => {
            // 若上一步操作返回了Promise实例则进入if语句块
              if( resp ) {
                const { success, message } = resp.data;
                if( success ) {
                  ElMessage({ message: `${message}!`, type: 'success'});
                  // 调用 customerStore 中提供的方法完成后续操作
                  customerStore.signIn(this.account, resp.data.token);
                  // 编程式导航到登录后的主页
                  this.$router.push({name: 'main'});
                  return;
                }
                ElMessage({ message: `警告:${message}!`, type: 'warning'});
              }
          }).catch(reason =>{
              ElMessage({ message: `登录失败！`, type: 'error'});
              console.log(reason);
          });
      }
  }
}
</script>

<template>
  <div class="wrapper">
    <h3>用户登录</h3>
    <el-form label-position="top">
        <el-form-item label="账号">
            <el-input v-model="account" />
        </el-form-item>
        <el-form-item label="登录密码">
            <el-input type="password" v-model="password" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<style scoped>
:global(body) {
  background: #f4f4f4;
}
.wrapper {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -15vw;
    margin-top: -155px;
    padding: 0 0.5vw;
    border-radius: 5px;
    background: #fff;
    width: 30vw;
    min-height: 310px;
}
</style>